<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="userName">
      <el-input v-model="loginForm.userName" placeholder="请输入工号/用户名/手机号">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button
      :icon="UserFilled"
      size="large"
      type="primary"
      :loading="loading"
      @click="loginHandler(loginFormRef)"
      style="width: 100%"
    >
      登 录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import type { LoginForm } from "@/typings";
import type { FormRules, FormInstance } from "element-plus";
import { ElMessage, ElNotification } from "element-plus";

import { ref, reactive, onMounted } from "vue";
import { User, UserFilled } from "@element-plus/icons-vue";
import { useKeepAliveStore, useTabsStore, useUserStore } from "@/stores";
import { login } from "@/api";
import { HOME_URL, SALUTATION } from "@/config";
import { useRouter } from "vue-router";
import { getTimeState, random } from "@/utils";
import md5 from "md5";

const loginFormRef = ref<FormInstance>();
const loading = ref(false);
const router = useRouter();
const useUser = useUserStore();
const useTabs = useTabsStore();
const useKeepAlive = useKeepAliveStore();
const codeUrl = ref("");
const loginForm: LoginForm = reactive({
  userName: "Admin",
  password: "123456"
});
const loginRules: FormRules<typeof loginForm> = reactive({
  userName: [
    { required: true, message: "用户名称不能为空!", trigger: "blur" },
    { min: 4, max: 16, message: "长度为 4 ~ 16 位!", trigger: "blur" }
  ],
  password: [
    { required: true, message: "用户密不能为空!", trigger: "blur" },
    { min: 6, max: 16, message: "密码的长度为 6 ~ 16 位!", trigger: "blur" }
  ]
});

/**
 * @description 登录处理
 * @param formEl 表单实例
 */
const loginHandler = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid: boolean) => {
    if (!valid) return;
    loading.value = true;
    try {
      const loginResult = await login(Object.assign(loginForm, { password: md5(loginForm.password) }));
      if (loginResult.code === 200) {
        ElMessage.success("登录成功");
        const { data } = loginResult;
        useUser.token = data.access_token;
        useUser.userInfo = data;
        useTabs.closeMultipleTab();
        useKeepAlive.setKeepAliveName();
        router.push(HOME_URL);
        ElNotification({
          title: "哈喽，" + useUser.userInfo.nickName + getTimeState(),
          message: SALUTATION[random(0, SALUTATION.length - 1)],
          type: "success",
          duration: 5000
        });
        return false;
      }
      // todo 判断验证码错误的时候从新刷新验证码
      ElMessage.error(loginResult.message);
    } catch (error) {
      ElMessage.error("登录失败，请稍后再试!");
    } finally {
      loading.value = false;
    }
  });
};


onMounted(async () => {
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      loginHandler(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";

.login-code {
  width: 40%;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  .login-code-img {
    cursor: pointer;
    height: 100%;
    vertical-align: middle;
  }
}
</style>
